package net.anzhuo.controller.db;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;
import net.anzhuo.common.utils.CompanyNameUtils;
import net.anzhuo.common.utils.DateUtil;
import net.anzhuo.common.utils.RedisUtil;
import net.anzhuo.entity.GsBase;
import net.anzhuo.entity.GsBranch;
import net.anzhuo.entity.GsChange;
import net.anzhuo.entity.GsCheck;
import net.anzhuo.entity.GsCompanyProducts;
import net.anzhuo.entity.GsCompanyTaxCredit;
import net.anzhuo.entity.GsContactInfo;
import net.anzhuo.entity.GsGudong;
import net.anzhuo.entity.GsMember;
import net.anzhuo.entity.GsOuttouzi;
import net.anzhuo.entity.GsPenaltyCreditChina;
import net.anzhuo.entity.GsPermission;
import net.anzhuo.entity.GsPledge;
import net.anzhuo.entity.GsPriority;
import net.anzhuo.entity.GsPunishment;
import net.anzhuo.entity.db.Branches;
import net.anzhuo.entity.db.ChangeRecords;
import net.anzhuo.entity.db.CompanyProducts;
import net.anzhuo.entity.db.CompanyTaxCreditItems;
import net.anzhuo.entity.db.ContactInfo;
import net.anzhuo.entity.db.DetailResult;
import net.anzhuo.entity.db.Employees;
import net.anzhuo.entity.db.Industry;
import net.anzhuo.entity.db.Partners;
import net.anzhuo.entity.db.Penalty;
import net.anzhuo.entity.db.PenaltyCreditChina;
import net.anzhuo.entity.db.Pledge;
import net.anzhuo.entity.db.Result;
import net.anzhuo.entity.db.SpotCheck;
import net.anzhuo.entity.db.WebSite;
import net.anzhuo.entity.db.common.ResponseResult;
import net.anzhuo.entity.db.syncdata.Permission;
import net.anzhuo.service.GsBaseService;
import net.anzhuo.service.GsBranchService;
import net.anzhuo.service.GsChangeService;
import net.anzhuo.service.GsCheckService;
import net.anzhuo.service.GsCompanyProductsService;
import net.anzhuo.service.GsCompanyTaxCreditService;
import net.anzhuo.service.GsContactInfoService;
import net.anzhuo.service.GsGudongService;
import net.anzhuo.service.GsMemberService;
import net.anzhuo.service.GsOuttouziService;
import net.anzhuo.service.GsPenaltyCreditChinaService;
import net.anzhuo.service.GsPermissionService;
import net.anzhuo.service.GsPledgeService;
import net.anzhuo.service.GsPriorityService;
import net.anzhuo.service.GsPunishmentService;

@RestController
@Slf4j
public class DetailController {

	@Autowired
	private GsBaseService gsBaseService;
	@Autowired
	private GsGudongService gsGudongService;
	@Autowired
	private GsMemberService gsMemberService;
	@Autowired
	private GsBranchService gsBranchService;
	@Autowired
	private GsChangeService gsChangeService;
	
	@Autowired
	private GsContactInfoService gsContactInfoService;
	
	@Autowired
	private GsOuttouziService gsOuttouziService;
	
	@Autowired
	private GsPunishmentService gsPunishmentService;
	
	
	@Autowired
	private GsPledgeService gsPledgeService;
	
	
	
	@Autowired
	private GsCompanyTaxCreditService gsCompanyTaxCreditService;
	
	
	
	@Autowired
	private GsCheckService gsCheckService;
	
	
	@Autowired
	private GsCompanyProductsService gsCompanyProductsService;
	
	@Autowired
	private GsPriorityService gsPriorityService;
	
	
	@Autowired
	private GsPenaltyCreditChinaService gsPenaltyCreditChinaService;
	
	@Autowired
	private GsPermissionService gsPermissionService;
	
	@RequestMapping("/detail")
	public DetailResult getDetail(String keyword) {
		log.info("===>getDetail_keyword="+keyword);
		GsPriority gp=new GsPriority();
		gp.setKeyNo(keyword);
		gp.setStatus("0");
		gp.setOperdate(DateUtil.getDate("yyyy-MM-dd"));
		int count=gsPriorityService.getCount(gp);
		if(count==0)
		{
		gsPriorityService.save(gp);
		}
		long startTime=System.currentTimeMillis();
		/*try {
			DetailResult dr = (DetailResult)RedisUtil.get("detail:"+keyword);
			if (dr != null) {
				 long endTime=System.currentTimeMillis();
				 float excTime=(float)(endTime-startTime)/1000;
				 log.info(" getDetail_keyword 执行时间："+excTime+"s");
				log.info("===>getDetail_keyword= redis is hitted!");
				return dr;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		DetailResult detailResult = new DetailResult();
		try {
	
		detailResult.setStatus("200");
		detailResult.setMessage("查询成功");
		
		
		
		Result result = new Result();
		GsBase gsBase = gsBaseService.getByMd5(keyword);
		result.setKeyNo(gsBase.getMd5());
		result.setName(gsBase.getName());
		result.setBelongOrg(gsBase.getRegAuth());
		result.setOperName(gsBase.getLegal());
		result.setStartDate(gsBase.getRegTime());
	    result.setEndDate(gsBase.getApprovalTime());
		result.setStatus(gsBase.getEnterpriseStatus());
		result.setProvince(gsBase.getProvince());
		result.setCreditCode(gsBase.getCreditCode());
		result.setRegistCapi(gsBase.getRegZb());
		result.setEconKind(gsBase.getEnterpriseType());
		result.setAddress(gsBase.getRegAddress());
		result.setScope(gsBase.getOperScope());
		result.setTermStart(gsBase.getBusinessStartTime());
		result.setTeamEnd(gsBase.getBusinessEndTime());
		result.setCheckDate(gsBase.getApprovalTime());
		result.setOrgNo(gsBase.getDeptCode());
		if(gsBase.getUpdateTime()==null||gsBase.getUpdateTime().trim().equals(""))
		{
			result.setUpdatedDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		}else
		{
		result.setUpdatedDate(gsBase.getUpdateTime());
		}
		log.info("deptcode="+gsBase.getDeptCode());
		result.setNo(gsBase.getRegNumber());
		log.info("regno="+gsBase.getRegNumber());
		List<GsGudong> gudongList = gsGudongService.getByMd5(keyword);
		log.info("gudonglist'size="+gudongList.size());
		Hashtable<String,GsGudong> hashMap=new Hashtable<String,GsGudong>();
		if (gudongList!=null && gudongList.size()>0) {
			List<Partners> partnersList = new ArrayList<>();
			Partners partners = null;
			for (GsGudong g : gudongList) {
				partners = new Partners();
				if(!hashMap.containsKey(g.getShareholder()))
						{
				partners.setStockName(g.getShareholder());
				partners.setStockPercent(g.getCapitalPercent());
				partners.setShouldCapi(g.getConfisCapital());
				partners.setShoudDate(g.getCapitaltime());
				partners.setStockType(g.getCapitaltype());
				partnersList.add(partners);
				hashMap.put(g.getShareholder(), g);
						}else
						{
							gsGudongService.deleteByID(g);
						}
			}
			Collections.sort(partnersList, new Comparator<Partners>() {
	            public int compare(Partners o1, Partners o2) {
	                return o1.getStockPercent().replace("%","").compareTo(o2.getStockPercent().replace("%",""));
	            }
	        });
			result.setPartners(partnersList);
		}
		
		List<GsMember> memberList = gsMemberService.getByMd5(keyword);
		log.info("member'size="+memberList.size());
		Hashtable<String,GsMember> hashMapmem=new Hashtable<String,GsMember>();
		if (memberList!=null && memberList.size()>0) {
			List<Employees> employeesList = new ArrayList<>();
			Employees employees = null;
			for (GsMember m : memberList) {
				String keys=m.getName()+m.getPosition();
				if(!hashMapmem.containsKey(keys))
				{
				employees = new Employees();
				employees.setName(m.getName());
				employees.setJob(m.getPosition());
				employeesList.add(employees);
				hashMapmem.put(keys, m);
				}else
				{
					gsMemberService.deleteByID(m);
				}
			}
			result.setEmployees(employeesList);
		}
		
		List<GsBranch> branchList = gsBranchService.getByMd5(keyword);
		log.info("branchList'size="+branchList.size());
	//	ConcurrentHashMap<String,GsBranch> hashMapBranch=new ConcurrentHashMap<String,GsBranch>();
		if (branchList!=null && branchList.size()>0) {
			List<Branches> branchesList = new ArrayList<>();
			Branches branches = null;
			for (GsBranch b : branchList) {
				
				//String keyBranch=b.getEnterpriseName();
				//if(!hashMapBranch.containsKey(keyBranch))
				//{
				GsBase branch = gsBaseService.getByMd5(b.getMd5());
				branches = new Branches();
				
				branches.setName(b.getEnterpriseName());
				branches.setCompanyId(b.getMd5());
				if(branch!=null)
				{
				branches.setCreditCode(branch.getCreditCode());
				branches.setRegNo(branch.getRegNumber());
				branches.setOperName(branch.getLegal());
				branches.setBelongOrg(branch.getRegAuth());
				}
				branchesList.add(branches);
				//hashMapBranch.put(keyBranch, b);
				//}else
				//{
				//gsBranchService.delete(b);
				//}
			}
			result.setBranches(branchesList);
		}
		
		List<GsChange> changeList = gsChangeService.getByMd5(keyword);
		log.info("changeList'size="+changeList.size());
		if (changeList!=null && changeList.size()>0) {
			List<ChangeRecords> changeRecordsList = new ArrayList<>();
			ChangeRecords changeRecords = null;
			for (GsChange c : changeList) {
				changeRecords = new ChangeRecords();
				changeRecords.setProjectName(c.getChangeProject());
				changeRecords.setBeforeContent(c.getChangeBefore());
				changeRecords.setAfterContent(c.getChangeAfter());
				changeRecords.setChangeDate(c.getChangeTime());
				changeRecordsList.add(changeRecords);
			}
			result.setChangeRecords(changeRecordsList);
		}
		//ContactInfo
		List<GsContactInfo> contactList=gsContactInfoService.getBycoMd5(keyword);
		  ContactInfo contactInfo=null;
		  contactInfo=new ContactInfo();
		  log.info("contact size="+contactList.size());
		//if(contactList!=null&&contactList.size()>0)
		//{
		
		  
		  List<WebSite> webSiteList=new ArrayList<WebSite>();
		  WebSite webSite=new WebSite();
		  
			 webSite=new WebSite();		 
			 webSite.setName("");
			 webSite.setUrl(gsBase.getWebSite());
			 webSiteList.add(webSite);

		  contactInfo.setWebSite(webSiteList);
		//}
		contactInfo.setPhoneNumber(gsBase.getTel());
		log.info("contactinfo phone="+contactInfo.getPhoneNumber());
		log.info("contactinfo email="+contactInfo.getEmail());
		contactInfo.setEmail(gsBase.getEmail());
		result.setContactInfo(contactInfo);
		//Penalty
		List<GsPunishment> punishmentList=gsPunishmentService.getBycoMd5(keyword);
		log.info("punishmentList's size="+punishmentList.size());
		List<Penalty> penaltyList=new ArrayList<Penalty>();
		if(punishmentList!=null&&punishmentList.size()>0)
		{
			Penalty penalty=new Penalty();
			for(GsPunishment c:punishmentList)
			{
				penalty=new Penalty();
				penalty.setDocNo(c.getDocNo());
				penalty.setOfficeName(c.getOfficeName());
				penalty.setContent(c.getContent());
				penalty.setPenaltyDate(c.getPenaltyDate());
				penalty.setPublicDate(c.getPublicDate());
				penalty.setRemark("");
				penaltyList.add(penalty);
			
			}
			
		}
		result.setPenalty(penaltyList);
		//Pledge
		List<GsPledge> pledgeList=gsPledgeService.getBycoMd5(keyword);
		List<Pledge>   pledge=new ArrayList<Pledge>();
		log.info("pledgeList's length="+pledgeList.size());
		if(pledgeList!=null&&pledgeList.size()>0)
		{
			Pledge p=new Pledge();
			for(GsPledge c:pledgeList)
			{
				p=new Pledge();
				p.setCompanyId(c.getCoMd5());
				p.setRegistNo(c.getRegistNo());
				p.setPledgor(c.getPledgor());
				p.setPledgee(c.getPledgee());
				p.setPledgeeNo(c.getPledgeeNo());
				p.setPledgedAmount(c.getPledgedAmount());
				p.setRegDate(c.getRegDate());
				p.setPublicDate(c.getPublicDate());
				p.setStatus(c.getStatus());
				pledge.add(p);
			}

		}
		result.setPledge(pledge);
		//CompanyTaxCreditItems
		List<GsCompanyTaxCredit> gsCompanyTaxCreditList=gsCompanyTaxCreditService.getBycoMd5(keyword);
		List<CompanyTaxCreditItems> companyTaxCreditItemsList=new ArrayList<CompanyTaxCreditItems>();
		if(gsCompanyTaxCreditList!=null&&gsCompanyTaxCreditList.size()>0)
		{
			CompanyTaxCreditItems cti=new CompanyTaxCreditItems();
			
			for(GsCompanyTaxCredit c:gsCompanyTaxCreditList)
			{
				
				cti=new CompanyTaxCreditItems();
				cti.setNo(c.getPaynumber());
				cti.setName(result.getName());
				cti.setYear(c.getYear());
				cti.setLevel(c.getPaygrade());
				cti.setGradeOrg(c.getEvaluationunit());
				cti.setTaxType(c.getType());
				companyTaxCreditItemsList.add(cti);
			}
			
		}
		
		result.setCompanyTaxCreditItems(companyTaxCreditItemsList);
		//SpotCheck
		List<GsCheck> gsCheckList=gsCheckService.getBycoMd5(keyword);
		List<SpotCheck> spotCheckList=new ArrayList<SpotCheck>();
		if(gsCheckList!=null&&gsCheckList.size()>0)
		{
			SpotCheck sc=new SpotCheck();
			
			for(GsCheck c:gsCheckList)
			{
				sc=new SpotCheck();
				sc.setExecutiveOrg(c.getChekreg());
				sc.setDate(c.getDatetime());
				sc.setType(c.getType());
				sc.setConsequence(c.getId()+"");
				sc.setNo(c.getMd5());
				sc.setRemark("");
				spotCheckList.add(sc);
			}
			
		}	
		result.setSpotCheck(spotCheckList);
		//CompanyProducts
		List<GsCompanyProducts> gsCompanyProductsList=gsCompanyProductsService.getBycoMd5(keyword);
		List<CompanyProducts> companyProducts=new ArrayList<CompanyProducts>();
		if(gsCompanyProductsList!=null&&gsCompanyProductsList.size()>0)
		{
		   CompanyProducts cp=new CompanyProducts();
		   for(GsCompanyProducts c:gsCompanyProductsList)
		   {
			   cp=new CompanyProducts();
			   cp.setCompanyName(c.getCompanyName());
			   cp.setLink(c.getLink());
			   cp.setImageUrl(c.getImageUrl());
			   cp.setName(c.getName());
			   cp.setDomain(c.getDomain());
			   cp.setTags(c.getTags());
			   cp.setDescription(c.getDescription());
			   cp.setCategory(c.getCategory());
			   companyProducts.add(cp);
		   }
		}
		
	    result.setCompanyProducts(companyProducts);
	    //PenaltyCreditChina
	    List<GsPenaltyCreditChina> gsPenaltyCreditChinaList=gsPenaltyCreditChinaService.getBycoMd5(keyword);
	    List<PenaltyCreditChina>   penaltyCreditChina=new ArrayList<PenaltyCreditChina>();
	    
	    if(gsPenaltyCreditChinaList!=null&&gsPenaltyCreditChinaList.size()>0)
	    {
	    	PenaltyCreditChina pcc=new PenaltyCreditChina();
	    	for(GsPenaltyCreditChina c:gsPenaltyCreditChinaList)
	    	{
	    		pcc=new PenaltyCreditChina();
	    		pcc.setCaseNo(c.getCaseNo());
	    		pcc.setLiandate(c.getLiandate());
	    		pcc.setName(c.getName());
	    		pcc.setOwnerName(c.getOwnerName());
	    		pcc.setProvince(c.getProvince());
	    		pcc.setCaseReason(c.getCaseReason());
	    		penaltyCreditChina.add(pcc);
	    	}    	
	    }
	    
	    result.setPenaltyCreditChina(penaltyCreditChina);
	    //outtouzi
	    GsOuttouzi ssOuttouziQuery = new GsOuttouzi();
		List<net.anzhuo.entity.db.outtouzi.Result> listOutzouzi=new ArrayList<net.anzhuo.entity.db.outtouzi.Result>();
		ssOuttouziQuery.setCoMd5(keyword);
		//ConcurrentHashMap<String,GsOuttouzi> hashMapGsOuttouzi=new ConcurrentHashMap<String,GsOuttouzi>();
		List<GsOuttouzi> outtouziList=gsOuttouziService.getList(ssOuttouziQuery);
		if (outtouziList!=null && outtouziList.size()>0) {
			for (GsOuttouzi o : outtouziList) {
				net.anzhuo.entity.db.outtouzi.Result	resultOut = new net.anzhuo.entity.db.outtouzi.Result();
			//	if(!hashMapGsOuttouzi.containsKey(o.getEnterpriseName()))
			//	{
				resultOut.setName(o.getEnterpriseName());
				resultOut.setNo(o.getMd5());
				resultOut.setStatus(o.getState());
				resultOut.setFundedRatio(o.getInvestmentRatio());
				resultOut.setRegistCapi(o.getRegCapital());
				resultOut.setOperName(o.getLegal());
				resultOut.setFundedRatio(o.getInvestmentRatio());
				resultOut.setStartDate(o.getRegTime());
				listOutzouzi.add(resultOut);
			//	hashMapGsOuttouzi.put(o.getEnterpriseName(), o);
			//	}else
			//	{
			//		gsOuttouziService.delete(o);
			//	}
				
			}
		}
		
		result.setInvestment(listOutzouzi);
		//permission
		List<GsPermission> permissionList=gsPermissionService.getBycoMd5(keyword);
		List<Permission> listPermission=new ArrayList<Permission>();
		if(permissionList!=null)
		{
			Permission pl=new Permission();
			for(GsPermission g:permissionList)
			{
				pl=new Permission();
				pl.setContent(g.getContent());
				pl.setLegal(g.getLegal());
				pl.setDecisionDate(g.getDecisionDate());
				pl.setName(g.getName());
				pl.setPermissionAgent(g.getPermissionAgent());
				pl.setPermissionNo(g.getPermissionNo());
				pl.setPermissionType(g.getType());
				pl.setPostNo(g.getPostNo());
				pl.setUpdateTime(g.getUpdateTime());
				pl.setStopDate(g.getStopDate());
				listPermission.add(pl);
			}
		}
		result.setPermissionInfo(listPermission);
		result.setPenalty(penaltyList);
		
	    //Industry
	    Industry industry=new Industry();
	    industry.setIndustry(gsBase.getIndustry());
	    result.setIndustry(industry);
		detailResult.setResult(result);
		}catch(Exception e1)
		{
			log.info(e1.getMessage());
		}
		
		try {
			RedisUtil.set("detail:"+keyword, detailResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
		 long endTime=System.currentTimeMillis();
		 float excTime=(float)(endTime-startTime)/1000;
		 log.info(" getDetail_keyword 执行时间："+excTime+"s");
		return detailResult;
	}
	
	@RequestMapping("/FetchKeyNoByName")
	public ResponseResult FetchKeyNoByName(String keyword) {
		long startTime=System.currentTimeMillis();
		log.info("===>FetchKeyNoByName="+keyword);
		try {
			ResponseResult dr = (ResponseResult)RedisUtil.get("FetchKeyNoByName:"+keyword);
			if (dr != null) {
				 long endTime=System.currentTimeMillis();
				 float excTime=(float)(endTime-startTime)/1000;
				 log.info(" FetchKeyNoByName 执行时间："+excTime+"s");
				log.info("===>FetchKeyNoByName= redis is hitted!");
				return dr;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		ResponseResult detailResult = new ResponseResult();
		try {
	   
		detailResult.setStatus("200");
		detailResult.setMessage("查询成功");
		String sEnglistName= CompanyNameUtils.getEnglishBraces(keyword);
		GsBase gsBase = gsBaseService.getByName(sEnglistName);
		if(gsBase!=null)
		{
			detailResult.setKeyNo(gsBase.getMd5());
		}else
		{
			String sChineseName= CompanyNameUtils.getEnglishBraces(keyword);
			 gsBase = gsBaseService.getByName(sChineseName);
			 if(gsBase!=null)
			 {
			detailResult.setKeyNo(gsBase.getName());
			 }else
			 {	
				 detailResult.setKeyNo("");
				 
			 }
		}
		}catch(Exception e1)
		{
			log.info(e1.getMessage());
		}
		
		try {
			RedisUtil.set("FetchKeyNoByName:"+keyword, detailResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
		 long endTime=System.currentTimeMillis();
		 float excTime=(float)(endTime-startTime)/1000;
		 log.info(" FetchKeyNoByName 执行时间："+excTime+"s");
		return detailResult;
	}
}
